package org.xhy.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.xhy.security.domain.Permission;
import org.xhy.security.domain.VipUser;
import org.xhy.security.mapper.PermissionMapper;
import org.xhy.security.mapper.UserMapper;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //判断参数
        if (!StringUtils.hasText(username)){
            throw new RuntimeException("用户名不能为空！");
        }

        //用户名查询
        VipUser vipUser = userMapper.selectByUsername(username);
        if (vipUser == null){
            throw new RuntimeException("用户名不存在！");
        }

        //查询所有的权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(vipUser.getId());

        //循环遍历 将 List<Permission> 转化成 List<GrantedAuthority>   ->   再成List<SimpleGrantedAuthority>
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
            return new SimpleGrantedAuthority(permission.getExpression()); //GrantedAuthority类是一个接口，new他的子类SimpleGrantedAuthority
        }).collect(Collectors.toList());//将每一个结果收集起来转化成List

        //List<GrantedAuthority> authorities = new ArrayList<>(); //user参数中需要一个authorities，new一个出来

        return new User(username,vipUser.getPassword(),
                vipUser.isEnabled(),
                vipUser.isAccountNonExpired(),
                vipUser.isCredentialsNonExpired(),
                vipUser.isAccountNonLocked(),
                authorities); //权限集合
    }
}
